﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DemoExcelWorkbook
{
    using Microsoft.Research.Kinect;
    using Microsoft.Research.Kinect.Nui;
    using KINECTUtility;

    public partial class KinectControl : UserControl
    {
        private Runtime runtime;
        private AreaChecker myAreaChecker;

        public KinectControl()
        {
            InitializeComponent();

        }

        private int unitHight;
        private int unitWidth;
        private int value;
        private void buttonKinect_Click(object sender, EventArgs e)
        {
            unitWidth = Int32.Parse(textBoxUnitWidth.Text);
            unitHight = Int32.Parse(textBoxUnitHeight.Text);
            value = Int32.Parse(textBoxValue.Text);

            myAreaChecker = new AreaChecker(640, 480, unitWidth, unitHight);
            myAreaChecker.HoldTime = TimeSpan.FromMilliseconds(3000);
            myAreaChecker.AreaMoved += new AreaChecker.AreaCheckerUpdateEventHandler(myAreaChecker_AreaMoved);
            myAreaChecker.AreaHold += new AreaChecker.AreaCheckerHoldEventHandler(myAreaChecker_AreaHold);
            
            runtime = new Runtime();
            runtime.Initialize(RuntimeOptions.UseSkeletalTracking);

            runtime.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(runtime_SkeletonFrameReady);
        }

        void runtime_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            var frame = e.SkeletonFrame;
            foreach (var data in frame.Skeletons)
            {
                if (data.TrackingState == SkeletonTrackingState.Tracked)
                {
                    myAreaChecker.BeginCheck();
                    myAreaChecker.IsIncludePoint(data.Joints[JointID.HandRight].Position.X, data.Joints[JointID.HandRight].Position.Y, JointID.HandRight);
                    myAreaChecker.EndCheck();
                    break;
                }
            }
        }

        void myAreaChecker_AreaHold(AreaCheckerHoldEventArgs e)
        {
            Globals.Sheet1.MultNumber(e.HoldIndexHorizontal, e.HoldIndexVertical, 3);
        }

        void myAreaChecker_AreaMoved(AreaCheckerUpdateEventArgs e)
        {
            Globals.Sheet1.Focus(e.CurrentIndexHorizontal, e.CurrentIndexVertical);
            Globals.Sheet1.SetNumber(e.CurrentIndexHorizontal, e.CurrentIndexVertical, value);
        }
    }
}
